﻿//------------------------------------------------------------------------------
// <copyright company="Tunynet">
//     Copyright (c) Tunynet Inc.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Tunynet;

namespace Tunynet.Search
{
    public static class SearcherFactory
    {
        public const string GlobalSearchCode = "GlobalSearcher";
        public const string GlobalSearchName = "所有";

        //以indexPath为key，存储SearchEngine实例
        public static ConcurrentDictionary<string, ISearchEngine> searchEngines = new ConcurrentDictionary<string, ISearchEngine>();

        /// <summary>
        /// 获取所有Searcher
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<ISearcher> GetSearchers()
        {
            return DIContainer.Resolve<IEnumerable<ISearcher>>().OrderBy(s => s.DisplayOrder);
        }

        /// <summary>
        /// 依据搜索器编码获取ISearcher
        /// </summary>
        /// <param name="code">搜索器的编码，各ISearcher的code必须唯一，以应用的ApplicationKey作为前缀，例如UserSearcher或User_Searcher</param>
        /// <returns><see cref="ISearcher"/></returns>
        public static ISearcher GetSearcher(string code)
        {
            //return DIContainer.Resolve<IEnumerable<ISearcher>>().Where(s => s.Code.Equals(code, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
            return DIContainer.ResolveNamed<ISearcher>(code);
        }

        /// <summary>
        /// 依据indexPath获取SearchEngine
        /// </summary>
        /// <param name="indexPath">索引路径</param>
        /// <returns></returns>
        public static ISearchEngine GetSearchEngine(string indexPath)
        {
            ISearchEngine searchEngine = null;

            if (!searchEngines.TryGetValue(indexPath, out searchEngine))
            {
                searchEngine = new SearchEngine(indexPath);
                searchEngines.TryAdd(indexPath, searchEngine);
            }

            return searchEngine;
        }
    }
}